import { defineStore } from "pinia";
import { login, logout, getLoginInfo, getActivity } from "@/api/user";
import PollingManager from "@/class/PollingManager";
import { clearStorageLoginInfo } from "@/utils/token";

const polling = new PollingManager(60 * 1000 * 10, getActivity);

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {
      username: "",
      nickname: "",
      id: "",
    },
  }),
  getters: {
    isLogin(state) {
      return !!state.userInfo.id;
    },
  },
  actions: {
    handleLogin(params: any) {
      return new Promise((resolve, reject) => {
        login({
          ...params,
        })
          .then((res: any) => {
            chrome.storage.sync
              .set({
                baoyiplus_accessToken: res.data.accessToken,
                baoyiplus_expiresIn: res.data.expiresIn,
              })
              .then(() => {
                resolve(res);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    handleUseCatchUserInfo() {
      chrome.storage.sync.get(["baoyiplus_userInfo"]).then((storageData) => {
        const { baoyiplus_userInfo } = storageData;
        if (baoyiplus_userInfo) {
          this.userInfo = baoyiplus_userInfo;
        }
      });
    },
    async getUserInfo() {
      return getLoginInfo()
        .then((res) => {
          this.userInfo = res.data;
          chrome.storage.sync.set({
            baoyiplus_userInfo: this.userInfo,
          });
          polling.start();
          return res.data;
        })
        .catch(() => {
          polling.stop();
          chrome.storage.sync.remove([
            "baoyiplus_userInfo",
            "baoyiplus_accessToken",
            "baoyiplus_expiresIn",
          ]);
        });
    },
    clearLoginInfo() {
      this.userInfo = {
        username: "",
        nickname: "",
        id: "",
      };
      return clearStorageLoginInfo();
    },

    async handleLogout() {
      await logout();
      polling.stop();
      this.clearLoginInfo();
    },
  },
});
